<?php

/**
 * @package Bike
 * @subpackage User
 */

/**
 * Class for handling users
 * @author Chrome
 * @package Bike
 * @subpackage User
 */
class Bike_Users_User implements Bike_Users_IUser {

	/**
	 * Anonymous user data
	 * @var array
	 */
	protected $anonymous = array(
		'id' => -1,
		'login' => 'Anonymous'
	);

	/**
	 * Current user data(default null)
	 * @var mixed
	 */
	protected $currentUser = null;

	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::getAnonymous()
	 */
	public function getAnonymous(){
		return $this->anonymous;
	}

	/**
	 * Get Session from Bike_Service_Locator
	 * @return Ambiguous
	 */
	protected function getSession(){
		return Bike_Service_Locator::getService('BO_Session');
	}
	
	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::getCurrentUser()
	 */
	public function getCurrentUser(){
		$session = $this->getSession();
		if(!$session->isStarted()){
			$session->begin();
		}
		$this->currentUser = $session->get('userData');
		if(null == $this->currentUser){
			$session->end();
		}
		if(empty($this->currentUser)){
			return $this->getAnonymous();
		}else{
			return $this->currentUser;
		}
	}

	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::getUserById()
	 */
	public function getUserById($id){
		$userData = Bike_Service_Locator::getService('Users')->getRecordsByConditions(array(array('field' => 'id', 'operation' => '=', 'value' => $id)), 0, 1);
		$data = array();
		foreach($userData['items'] as $item){
			$data = $item;
		}
		return $data;
	}

	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::getUserByLogin()
	 */
	public function getUserByLogin($login){
		$userData = Bike_Service_Locator::getService('Users')->getRecordsByConditions(array(array('field' => 'login', 'operation' => '=', 'value' => $login)), 0, 1);
		$data = array();
		foreach($userData['items'] as $item){
			$data = $item;
		}
		return $data;
	}

	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::encodePassword()
	 */
	public function encodePassword($plainTextPassword){
		return md5($plainTextPassword);
	}

	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::authenticate()
	 */
	public function authenticate($login, $password){
		$userData = Bike_Service_Locator::getService('Users')->getRecordsByConditions(array(array('field' => 'login', 'operation' => '=', 'value' => (string)$login), array('field' => 'password', 'operation' => '=', 'value' => (string)$this->encodePassword($password))), 0, 1);
		$data = array();
		foreach($userData['items'] as $item){
			$data = $item;
		}
		$this->currentUser = $data;
		$session = $this->getSession();
		if(!empty($data)){
			$session->begin();
			$session->set('userData', $data);
		}
		return !empty($data);
	}

	/* (non-PHPdoc)
	 * @see Bike_Users_IUser::logout()
	 */
	public function logout(){
		$session = $this->getSession();
		if(!$session->isStarted()){
			$session->begin();
		}
		$session->end();
		$this->currentUser = null;
		return true;
	}
}
